package club.caihappy.springsecuritydemo.config;

import club.caihappy.springsecuritydemo.handle.MyAccessDeniedHandler;
import club.caihappy.springsecuritydemo.handle.MyAuthenticationFailureHandler;
import club.caihappy.springsecuritydemo.handle.MyAuthenticationSuccessHandler;
import club.caihappy.springsecuritydemo.service.MyServiceImpl;
import club.caihappy.springsecuritydemo.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.print.DocFlavor;
import javax.sql.DataSource;

/**
 * Created by DELL on 2022/5/8
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

//    @Autowired
//    private  DataSource dataSource;

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //表单提交
        http.formLogin()
                .passwordParameter("pwd")
                //放发现/login时认为是登陆，必须和表单提交的地址一样，去执行UserDetailsServiceImpl
                .loginProcessingUrl("/login")
                //自定义登陆页面
                .loginPage("/login.html")
                //登陆失败跳转页面，post请求
                .failureForwardUrl("/toError")
                //登陆成功跳转页面，post请求
                .successForwardUrl("/toMain");
        //登录后成功处理器，不能和successForwardUrl共存
//                .successHandler(new MyAuthenticationSuccessHandler("/main.html"))
        //登录后失败处理器，不能和failureForwardUrl共存
//                .failureHandler(new MyAuthenticationFailureHandler("/error.html"));
        //授权认证
        http.authorizeRequests()
                //白名单
//                .antMatchers("/login.html").permitAll()
                .antMatchers("/login.html").access("permitAll()")
//                .antMatchers("/error.html").permitAll()
                .antMatchers("/error.html").access("permitAll()")
//                .antMatchers(HttpMethod.POST, "/demo").permitAll()
                .regexMatchers(HttpMethod.POST, "/demo").permitAll()
//                .antMatchers("/js/**","/css/**","/images/**").permitAll()
//                .antMatchers("/**/*.png").permitAll()
                .regexMatchers(".+[.]png").permitAll()
                //所有请求都必须被身份认证,必须登陆之后被访问
//                .mvcMatchers("/demo").servletPath("/xxxx").permitAll()
//                .antMatchers("/xxxx/demo").permitAll()
//                .antMatchers("/main1.html").hasAuthority("admiN")
//                .antMatchers("/main1.html").hasAnyAuthority("admin","admiN")
//                .antMatchers("/main1.html").hasRole("abc")
//                .antMatchers("/main1.html").hasAnyRole("abc","ABC")
//                .antMatchers("/main1.html").hasIpAddress("127.0.0.1")
//                .antMatchers("/main1.html").access("hasIpAddress('127.0.0.1')")
                .anyRequest().authenticated();
//                .anyRequest().access("@myServiceImpl.hasPermission(request,authentication)");
        //关闭csrf防护
//        http.csrf().disable();

        //异常处理
        http.exceptionHandling()
                .accessDeniedHandler(myAccessDeniedHandler);

        http.rememberMe()
                //失效时间，秒
                .tokenValiditySeconds(60)
                //自定义登录逻辑
                .userDetailsService(userDetailsService)
                //持久层对象
                .tokenRepository(persistentTokenRepository);

        http.logout()
                //退出登录跳转页面
                .logoutSuccessUrl("/login.html");

    }

//    @Bean
//    public  PersistentTokenRepository getPersistentTokenRepository() {
//        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
//        jdbcTokenRepository.setDataSource(dataSource);
//        //自动建表，第一次启动时需要，第二次启动注释掉
//        jdbcTokenRepository.setCreateTableOnStartup(true);
//        return jdbcTokenRepository;
//    }

}
